<template>
    <div>
        <el-form :model="params">
            <el-row :gutter="12">
                <el-col :span="6">
                    <el-form-item label="库位编码">
                        <el-input v-model="params.warehouseLocationCode" placeholder="请输入库位编码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="库位名称">
                        <el-input v-model="params.warehouseLocationName" placeholder="请输入库位名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
            </el-row>

            <el-button style="background-color:#ADD8E6" @click="insert" :icon="Plus">新增</el-button>
            <el-button style=" background-color: #90EE90" :icon="Edit" @click="updateid"
                :disabled="isSingleRowSelected">修改</el-button>
            <el-button style="background-color: #FFCCCB" @click="Delete1" plain :disabled="deleteDisabled"
                :icon="Delete">删除</el-button>

            <div style="display: flex; flex-direction: column; gap: 20px;">
                <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" :selectable="selectable" width="50"></el-table-column>
                    <el-table-column prop="warehouseLocationCode" label="库位编码" width="150"></el-table-column>
                    <el-table-column prop="warehouseLocationName" label="库位名称" width="150"></el-table-column>
                    <el-table-column prop="area" label="面积" width="150"></el-table-column>
                    <el-table-column prop="payload" label="最大载重量" width="150"></el-table-column>
                    <el-table-column prop="status" label="是否启用" width="150" v-slot="options">
                        <el-tag :type="options.row.status == '0' ? 'success' : 'danger'">
                            {{ options.row.status == '0' ? '是' : '否' }}
                        </el-tag>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" width="200"></el-table-column>
                    <el-table-column label="操作" width="250px">
                        <template #default="scope">
                            <el-button type="primary" link @click="update(scope.row)" :icon="Edit">修改</el-button>
                            <el-button type="primary" link @click="Delete2(scope.row)" :icon="Delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-row>
                <el-col :span="24">
                    <div class="demo-pagination-block">
                        <el-pagination v-if="pageResult && pageResult.total !== undefined"
                            :current-page="params.currentPage" :page-size="params.pageSize" background
                            :default-page-size="params.pageSize" :page-sizes="pageSizes"
                            layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
        </el-form>


        <!-- 弹窗 -->
        <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="50%" @close="handleClose">
            <el-form ref="form" :model="formdata" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="库位编码">
                            <el-input v-model="formdata.warehouseLocationCode" placeholder="请输入库位编码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库位名称">
                            <el-input v-model="formdata.warehouseLocationName" placeholder="请输入库位名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="面积">
                            <el-input-number v-model="formdata.area" @change="handleChange" :min="0" :max="2000"
                                label="面积"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="最大载重量">
                            <el-input-number v-model="formdata.payload" @change="handleChange" :min="0" :max="2000"
                                label="最大载重量"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否启用" label-width="120px">
                            <el-radio-group v-model="formdata.status">
                                <el-radio value="0">是</el-radio>
                                <el-radio value="1">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注">
                            <el-input v-model="formdata.remark" placeholder="请输入备注" type="textarea" autosize></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                    <el-button @click="close">关闭</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { findLocations, insertLocations, updateLocations, deleteLocations } from '@/apis/xms/index';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Delete, Plus, Edit } from '@element-plus/icons-vue';

const salesorder = ref([]); // 表格数据
const pageResult = ref({}); // 初始值包含 total 属性
const title = ref(""); // 弹窗标题
const visible = ref(false); // 弹窗状态
const deleteDisabled = ref(true); // 删除按钮禁用状态,默认禁用
const ids = ref([]); // 选中行的id数组
const isSingleRowSelected = ref(true) // 修改按钮禁用状态,默认禁用
let roleVal = ref([]); //选中行
const route = useRoute();
const pageSizes = [2, 5, 8, 10];
const params = ref({
    currentPage: 1,
    pageSize: 5,
    warehouseAreaId: route.params.id,
    warehouseLocationCode: '',
    warehouseLocationName: '',
});
const formdata = ref({
    warehouseLocationCode: '',
    warehouseLocationName: '',
    area: 0,
    payload: 0,
    status: 0,
    remark: '',
    warehouseAreaId: route.params.id,
});

// 搜索条件
const handleSearch = async () => {
    try {
        const result = await findLocations(params.value);
        if (result && result.total !== undefined && result.records !== undefined) {
            pageResult.value = result;
            salesorder.value = result.records;
        } else {
            ElMessage.error('获取数据失败');
        }
    } catch (error) {
        ElMessage.error('搜索失败');
    }
};

// 处理分页大小
const handleSizeChange = async (size) => {
    params.value.pageSize = size;
    await handleSearch();
};

// 处理当前分页数据
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage;
    await handleSearch();
};

onMounted(async () => {
    await handleSearch();
});


/**
 * 新增
 */
const insert = () => {
    visible.value = true;
    title.value = '新增库位';

}
/**
 * 修改
 */
const update = (row) => {
    visible.value = true;
    title.value = '修改库位';
    formdata.value = { ...row };
}

const updateid = () => {
    visible.value = true;
    title.value = '修改库位';

}

/**
 * 提交
 */
const onSubmit = async () => {
    try {
        if (title.value === '新增库位') {
            await insertLocations(formdata.value);
            ElMessage.success('新增成功');
            visible.value = false;
            handleSearch();
        } else {
            await updateLocations(formdata.value);
            ElMessage.success('修改成功');
            visible.value = false;
            handleSearch();
        }
    } catch (error) {
        ElMessage.error('操作失败');
    }
};


const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length;
    ids.value = val.map(item => item.warehouseLocationId);

    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        formdata.value = { ...val[0] };//把选中的这条数据添加给修改数据（）
    }
};

const Delete1 = async () => {
    if (ids.value.length === 0) return;
    ElMessageBox.confirm(`是否确认删除编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteLocations(ids.value);
        ElMessage({ type: 'success', message: '删除成功' });
        ids.value = [];
        await handleSearch();
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};

const Delete2 = async (row) => {
    ElMessageBox.confirm(`是否确认删除编号为${row.warehouseLocationId}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteLocations([row.warehouseLocationId]);
        ElMessage({ type: 'success', message: '删除成功' });
        await handleSearch();
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};



const selectable = (row) => {
    return true;
};

const handleClose = () => {
    resetData();
};

const resetData = () => {
    formdata.value = {
        warehouseAreaId: '',
        warehouseAreaCode: '',
        warehouseAreaName: '',
        area: null,
        remark: ''
    };
    title.value = '';
};

const close = () => {
    visible.value = false;
    handleSearch();
};

const paramsReset = () => {
    params.value = {
        currentPage: 1,
        pageSize: 5,
        warehouseAreaId: route.params.id,
        warehouseLocationCode: '',
        warehouseLocationName: '',
    };
    handleSearch();
};
</script>

<style scoped>
.demo-pagination-block {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>